#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
阿里宝宝电商平台 - Web API服务器
提供RESTful API接口支持前端应用
"""

from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import json
import os
import sys
from datetime import datetime
import hashlib
import uuid

# 添加项目路径
current_dir = os.path.dirname(os.path.abspath(__file__))
ali_bao_bao_dir = os.path.dirname(current_dir)  # web_frontend的父目录就是ali_bao_bao
models_dir = os.path.join(ali_bao_bao_dir, "models")

if ali_bao_bao_dir not in sys.path:
    sys.path.insert(0, ali_bao_bao_dir)
if models_dir not in sys.path:
    sys.path.insert(0, models_dir)

# 导入后端模块
try:
    from integrated_system import user_manager, Product
    from cart import Cart, CartItem
    from order import Order, OrderManager
    from recommendation_system import recommendation_system
except ImportError as e:
    print(f"导入后端模块失败: {e}")
    print("请确保后端模块文件存在且路径正确")
    sys.exit(1)

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 全局变量
current_user = None
order_manager = OrderManager()

@app.route('/')
def index():
    """首页 - 返回静态HTML文件"""
    return render_template('index.html')

@app.route('/api/auth/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return jsonify({'success': False, 'error': '用户名和密码不能为空'}), 400
        
        user, message = user_manager.login_user(username, password)
        
        if user:
            # 生成简单的token
            token = hashlib.md5(f"{user.user_id}{datetime.now()}".encode()).hexdigest()
            
            return jsonify({
                'success': True,
                'data': {
                    'user_id': user.user_id,
                    'username': user.username,
                    'email': user.email,
                    'phone': user.phone,
                    'user_type': user.user_type,
                    'token': token
                }
            })
        else:
            return jsonify({'success': False, 'error': message}), 401
            
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/auth/register', methods=['POST'])
def register():
    """用户注册"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        email = data.get('email')
        phone = data.get('phone')
        user_type = data.get('userType', 'Customer')
        shop_name = data.get('shopName', '')
        
        if not all([username, password, email, phone]):
            return jsonify({'success': False, 'error': '所有字段都是必填的'}), 400
        
        kwargs = {}
        if user_type == 'Seller' and shop_name:
            kwargs['shop_name'] = shop_name
        
        user, message = user_manager.register_user(user_type, username, password, email, phone, **kwargs)
        
        if user:
            token = hashlib.md5(f"{user.user_id}{datetime.now()}".encode()).hexdigest()
            
            return jsonify({
                'success': True,
                'data': {
                    'user_id': user.user_id,
                    'username': user.username,
                    'email': user.email,
                    'phone': user.phone,
                    'user_type': user.user_type,
                    'token': token
                }
            })
        else:
            return jsonify({'success': False, 'error': message}), 400
            
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/products', methods=['GET'])
def get_products():
    """获取商品列表"""
    try:
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 12))
        category = request.args.get('category')
        
        # 获取所有商品
        all_products = Product._load_all_products()
        
        # 按分类过滤
        if category:
            all_products = [p for p in all_products if p.kind == category]
        
        # 分页
        start = (page - 1) * limit
        end = start + limit
        products = all_products[start:end]
        
        # 转换为API格式
        product_list = []
        for product in products:
            product_list.append({
                'id': product.id,
                'name': product.name,
                'price': product.prize,
                'category': product.kind,
                'location': product.province,
                'merchant_id': product.merchant_id,
                'description': f"优质{product.name}，产地{product.province}",
                'image': f"https://via.placeholder.com/300x200?text={product.name}",
                'average_rating': 4.5,
                'review_count': 128
            })
        
        return jsonify({
            'success': True,
            'data': {
                'products': product_list,
                'total': len(all_products),
                'page': page,
                'limit': limit,
                'has_more': end < len(all_products)
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/products/<product_id>', methods=['GET'])
def get_product_detail(product_id):
    """获取商品详情"""
    try:
        product = Product.from_id(product_id)
        
        if not product:
            return jsonify({'success': False, 'error': '商品不存在'}), 404
        
        # 模拟商品详情数据
        product_detail = {
            'id': product.id,
            'name': product.name,
            'price': product.prize,
            'original_price': product.prize * 1.2,  # 模拟原价
            'category': product.kind,
            'location': product.province,
            'merchant_id': product.merchant_id,
            'description': f"优质{product.name}，产地{product.province}，采用传统工艺制作，品质保证。",
            'images': [
                f"https://via.placeholder.com/600x400?text={product.name}主图",
                f"https://via.placeholder.com/600x400?text={product.name}细节1",
                f"https://via.placeholder.com/600x400?text={product.name}细节2",
                f"https://via.placeholder.com/600x400?text={product.name}包装"
            ],
            'specifications': {
                '产地': product.province,
                '净重': '5kg',
                '保质期': '12个月',
                '储存方式': '阴凉干燥处',
                '包装': '真空包装'
            },
            'average_rating': 4.5,
            'review_count': 128,
            'stock': 999  # 模拟库存
        }
        
        return jsonify({
            'success': True,
            'data': product_detail
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/products/search', methods=['POST'])
def search_products():
    """搜索商品"""
    try:
        data = request.get_json()
        keyword = data.get('keyword', '')
        filters = data.get('filters', {})
        
        if not keyword:
            return jsonify({'success': False, 'error': '搜索关键词不能为空'}), 400
        
        # 使用后端的模糊搜索
        products = Product.fuzzy_search(keyword)
        
        # 应用额外过滤器
        if filters.get('category'):
            products = [p for p in products if p.kind == filters['category']]
        
        if filters.get('min_price'):
            products = [p for p in products if p.prize >= filters['min_price']]
        
        if filters.get('max_price'):
            products = [p for p in products if p.prize <= filters['max_price']]
        
        # 转换为API格式
        product_list = []
        for product in products[:20]:  # 限制返回数量
            product_list.append({
                'id': product.id,
                'name': product.name,
                'price': product.prize,
                'category': product.kind,
                'location': product.province,
                'merchant_id': product.merchant_id,
                'description': f"优质{product.name}，产地{product.province}",
                'image': f"https://via.placeholder.com/300x200?text={product.name}",
                'average_rating': 4.5,
                'review_count': 128
            })
        
        return jsonify({
            'success': True,
            'data': {
                'products': product_list,
                'total': len(product_list),
                'keyword': keyword
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/cart', methods=['GET'])
def get_cart():
    """获取购物车"""
    try:
        # 这里应该根据用户ID获取购物车
        # 简化处理，返回空购物车
        return jsonify({
            'success': True,
            'data': {
                'items': [],
                'total': 0
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/cart/add', methods=['POST'])
def add_to_cart():
    """添加到购物车"""
    try:
        data = request.get_json()
        product_id = data.get('productId')
        quantity = data.get('quantity', 1)
        
        if not product_id:
            return jsonify({'success': False, 'error': '商品ID不能为空'}), 400
        
        # 验证商品存在
        product = Product.from_id(product_id)
        if not product:
            return jsonify({'success': False, 'error': '商品不存在'}), 404
        
        # 这里应该将商品添加到用户的购物车
        # 简化处理，直接返回成功
        
        return jsonify({
            'success': True,
            'data': {
                'message': '商品已添加到购物车',
                'product_id': product_id,
                'quantity': quantity
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/orders', methods=['GET'])
def get_orders():
    """获取用户订单"""
    try:
        # 这里应该根据用户ID获取订单
        # 简化处理，返回空订单列表
        
        return jsonify({
            'success': True,
            'data': {
                'orders': []
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/orders/create', methods=['POST'])
def create_order():
    """创建订单"""
    try:
        data = request.get_json()
        
        # 验证必要字段
        required_fields = ['items', 'shippingAddress', 'paymentMethod']
        for field in required_fields:
            if field not in data:
                return jsonify({'success': False, 'error': f'缺少必要字段: {field}'}), 400
        
        # 生成订单号
        order_number = f"ORD{int(datetime.now().timestamp())}{uuid.uuid4().hex[:6].upper()}"
        
        # 计算总金额
        total_amount = 0
        for item in data['items']:
            product = Product.from_id(item['productId'])
            if product:
                total_amount += product.prize * item['quantity']
        
        # 添加运费
        shipping_fee = 15.00
        total_amount += shipping_fee
        
        # 应用折扣
        discount = data.get('discount', 0)
        if discount > 0:
            total_amount = total_amount * (1 - discount / 100)
        
        # 创建订单数据
        order_data = {
            'order_number': order_number,
            'items': data['items'],
            'shipping_address': data['shippingAddress'],
            'payment_method': data['paymentMethod'],
            'total_amount': round(total_amount, 2),
            'shipping_fee': shipping_fee,
            'discount': discount,
            'status': 'Processing',
            'created_at': datetime.now().isoformat(),
            'estimated_delivery': (datetime.now().timestamp() + 3 * 24 * 3600)  # 3天后
        }
        
        return jsonify({
            'success': True,
            'data': order_data
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/recommendations', methods=['GET'])
def get_recommendations():
    """获取推荐商品"""
    try:
        user_id = request.args.get('userId')
        limit = int(request.args.get('limit', 10))
        
        # 获取推荐商品
        if user_id:
            recommendations = recommendation_system.get_recommendations(user_id, limit)
        else:
            # 如果没有用户ID，返回热门商品
            all_products = Product._load_all_products()
            recommendations = all_products[:limit]
        
        # 转换为API格式
        product_list = []
        for product in recommendations:
            product_list.append({
                'id': product.id,
                'name': product.name,
                'price': product.prize,
                'category': product.kind,
                'location': product.province,
                'merchant_id': product.merchant_id,
                'description': f"优质{product.name}，产地{product.province}",
                'image': f"https://via.placeholder.com/300x200?text={product.name}",
                'average_rating': 4.5,
                'review_count': 128
            })
        
        return jsonify({
            'success': True,
            'data': {
                'products': product_list,
                'type': 'recommendations' if user_id else 'trending'
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/categories', methods=['GET'])
def get_categories():
    """获取商品分类"""
    try:
        categories = [
            {'id': 'Food', 'name': '食品', 'icon': 'fas fa-utensils'},
            {'id': 'Clothing', 'name': '服装', 'icon': 'fas fa-tshirt'},
            {'id': 'Book', 'name': '图书', 'icon': 'fas fa-book'},
            {'id': 'Electronic Products', 'name': '电子产品', 'icon': 'fas fa-laptop'},
            {'id': 'Daily product', 'name': '日用品', 'icon': 'fas fa-home'}
        ]
        
        return jsonify({
            'success': True,
            'data': {
                'categories': categories
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.errorhandler(404)
def not_found(error):
    """404错误处理"""
    return jsonify({'success': False, 'error': '接口不存在'}), 404

@app.route('/api/seller/stats', methods=['GET'])
def get_seller_stats():
    """获取卖家统计数据"""
    try:
        # 模拟统计数据
        stats = {
            'total_products': 25,
            'total_orders': 156,
            'total_revenue': 12580.50,
            'avg_rating': 4.6,
            'pending_orders': 5,
            'completed_orders': 151
        }
        
        return jsonify({
            'success': True,
            'data': stats
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/products', methods=['GET'])
def get_seller_products():
    """获取卖家的商品列表"""
    try:
        seller_id = request.args.get('sellerId')
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 12))
        
        # 获取所有商品
        all_products = Product._load_all_products()
        
        # 按卖家ID过滤
        if seller_id:
            all_products = [p for p in all_products if p.merchant_id == seller_id]
        
        # 分页
        start = (page - 1) * limit
        end = start + limit
        products = all_products[start:end]
        
        # 转换为API格式
        product_list = []
        for product in products:
            product_list.append({
                'id': product.id,
                'name': product.name,
                'price': product.prize,
                'category': product.kind,
                'location': product.province,
                'merchant_id': product.merchant_id,
                'description': f"优质{product.name}，产地{product.province}",
                'image': f"https://via.placeholder.com/300x200?text={product.name}",
                'stock': 999,  # 模拟库存
                'created_at': '2024-01-01T00:00:00Z'
            })
        
        return jsonify({
            'success': True,
            'data': {
                'products': product_list,
                'total': len(all_products),
                'page': page,
                'limit': limit,
                'has_more': end < len(all_products)
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/products', methods=['POST'])
def create_seller_product():
    """创建新商品"""
    try:
        data = request.get_json()
        
        # 验证必要字段
        required_fields = ['name', 'price', 'category', 'location', 'stock']
        for field in required_fields:
            if field not in data:
                return jsonify({'success': False, 'error': f'缺少必要字段: {field}'}), 400
        
        # 创建商品数据
        product_data = {
            'id': f"PROD{int(datetime.now().timestamp())}",
            'name': data['name'],
            'price': float(data['price']),
            'category': data['category'],
            'location': data['location'],
            'stock': int(data['stock']),
            'description': data.get('description', ''),
            'merchant_id': data.get('merchantId', 'SELLER001'),
            'created_at': datetime.now().isoformat()
        }
        
        return jsonify({
            'success': True,
            'data': product_data
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/products/<product_id>', methods=['PUT'])
def update_seller_product(product_id):
    """更新商品信息"""
    try:
        data = request.get_json()
        
        # 模拟更新商品
        product_data = {
            'id': product_id,
            'name': data.get('name', '商品名称'),
            'price': data.get('price', 0),
            'category': data.get('category', 'Food'),
            'location': data.get('location', '未知'),
            'stock': data.get('stock', 0),
            'description': data.get('description', ''),
            'updated_at': datetime.now().isoformat()
        }
        
        return jsonify({
            'success': True,
            'data': product_data
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/products/<product_id>', methods=['DELETE'])
def delete_seller_product(product_id):
    """删除商品"""
    try:
        # 模拟删除商品
        return jsonify({
            'success': True,
            'data': {
                'message': '商品删除成功',
                'product_id': product_id
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/orders', methods=['GET'])
def get_seller_orders():
    """获取卖家的订单列表"""
    try:
        seller_id = request.args.get('sellerId')
        status = request.args.get('status')
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        
        # 模拟订单数据
        orders = [
            {
                'id': 'ORD20241201001',
                'order_number': 'ORD20241201001',
                'customer_name': '张**',
                'customer_phone': '138****0001',
                'product_name': '优质苹果',
                'quantity': 2,
                'unit_price': 25.00,
                'total_amount': 50.00,
                'status': 'Processing',
                'created_at': '2024-12-01T10:00:00Z',
                'shipping_address': '北京市朝阳区xxx街道xxx号'
            },
            {
                'id': 'ORD20241201002',
                'order_number': 'ORD20241201002',
                'customer_name': '李**',
                'customer_phone': '138****0002',
                'product_name': '新鲜橙子',
                'quantity': 3,
                'unit_price': 18.00,
                'total_amount': 54.00,
                'status': 'Shipped',
                'created_at': '2024-12-01T11:00:00Z',
                'shipping_address': '上海市浦东新区xxx路xxx号'
            }
        ]
        
        # 按状态过滤
        if status:
            orders = [o for o in orders if o['status'].lower() == status.lower()]
        
        return jsonify({
            'success': True,
            'data': {
                'orders': orders,
                'total': len(orders),
                'page': page,
                'limit': limit
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/shop', methods=['GET'])
def get_seller_shop():
    """获取卖家店铺信息"""
    try:
        # 模拟店铺信息
        shop_info = {
            'id': 'SHOP001',
            'name': '优质农产品店',
            'description': '专业销售优质农产品，品质保证，新鲜直达。',
            'logo': 'https://via.placeholder.com/100x100?text=店铺Logo',
            'address': '北京市朝阳区xxx街道xxx号',
            'phone': '138-0000-0000',
            'email': 'shop@example.com',
            'created_at': '2024-01-01T00:00:00Z'
        }
        
        return jsonify({
            'success': True,
            'data': shop_info
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/shop', methods=['PUT'])
def update_seller_shop():
    """更新卖家店铺信息"""
    try:
        data = request.get_json()
        
        # 模拟更新店铺信息
        shop_info = {
            'id': 'SHOP001',
            'name': data.get('name', '优质农产品店'),
            'description': data.get('description', ''),
            'logo': data.get('logo', ''),
            'address': data.get('address', ''),
            'phone': data.get('phone', ''),
            'email': data.get('email', ''),
            'updated_at': datetime.now().isoformat()
        }
        
        return jsonify({
            'success': True,
            'data': shop_info
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.errorhandler(404)
def not_found(error):
    """404错误处理"""
    return jsonify({'success': False, 'error': '接口不存在'}), 404

@app.errorhandler(500)
def internal_error(error):
    """500错误处理"""
    return jsonify({'success': False, 'error': '服务器内部错误'}), 500

if __name__ == '__main__':
    print("="*60)
    print("阿里宝宝电商平台 - Web API服务器")
    print("="*60)
    print("正在启动服务器...")
    print("API文档:")
    print("  POST /api/auth/login - 用户登录")
    print("  POST /api/auth/register - 用户注册")
    print("  GET  /api/products - 获取商品列表")
    print("  GET  /api/products/<id> - 获取商品详情")
    print("  POST /api/products/search - 搜索商品")
    print("  GET  /api/cart - 获取购物车")
    print("  POST /api/cart/add - 添加到购物车")
    print("  GET  /api/orders - 获取订单")
    print("  POST /api/orders/create - 创建订单")
    print("  GET  /api/recommendations - 获取推荐商品")
    print("  GET  /api/categories - 获取商品分类")
    print("="*60)
    
    # 启动Flask服务器
    app.run(
        host='0.0.0.0',
        port=8000,
        debug=True,
        threaded=True
    )
